package com.huiying.service.Impl;

import com.huiying.entity.entity.Like;
import com.huiying.mapper.LikeMapper;
import com.huiying.service.LikePersistenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: lsh
 * @Date: 2024/12/05/23:23
 * @Description: 点赞数据持久化
 */

@Service
@Slf4j
public class LikePersistenceServiceImpl implements LikePersistenceService {

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Async
    @Transactional
    public void saveLikeToMySQL(Long contentId, String contentType) {
        SetOperations<String, String> setOps = redisTemplate.opsForSet();
        String key = contentType.equals("0") ? "demand" + contentId : "work" + contentId;

        // 获取 Redis 中的点赞用户集合
        Set<String> redisUserIds = Optional.ofNullable(setOps.members(key)).orElse(new HashSet<>());

        // 从数据库获取当前点赞的用户 ID 列表
        List<Long> likedUserIds = likeMapper.getUserIdsByContentId(contentId, contentType);

        // 将数据库中的点赞用户 ID 转换为字符串集合
        Set<String> likedUserIdsSet = likedUserIds.stream()
                .map(String::valueOf)
                .collect(Collectors.toSet());

        // 需要删除的点赞用户：存在于数据库但不在 Redis 中
        Set<String> userIdsToDelete = new HashSet<>(likedUserIdsSet);
        userIdsToDelete.removeAll(redisUserIds);  // 从数据库中删除那些已经不在 Redis 中的用户

        // 需要新增的点赞用户：存在于 Redis 中但不在数据库中
        Set<String> userIdsToAdd = new HashSet<>(redisUserIds);
        userIdsToAdd.removeAll(likedUserIdsSet);  // 从 Redis 中删除那些不在数据库中的用户

        log.info("From Redis: {} users, to add: {} users, to delete: {} users", redisUserIds.size(), userIdsToAdd.size(), userIdsToDelete.size());

        // 1. 删除取消点赞的记录
        if (!userIdsToDelete.isEmpty()) {
            removeDislikedLikes(contentId, contentType, userIdsToDelete);
        }

        // 2. 保存新的点赞记录到数据库
        if (!userIdsToAdd.isEmpty()) {
            saveNewLikes(contentId, userIdsToAdd, contentType);
        }
    }


    private void removeDislikedLikes(Long contentId, String contentType, Set<String> userIdsToDelete) {
        // 将 userIdsToDelete 转换成 Long 类型的列表
        List<Long> userIdList = userIdsToDelete.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 批量查询所有符合条件的 id
        List<Long> deleteIds = likeMapper.getIdsByContentIdsAndUsers(contentId, contentType, userIdList);

        // 批量删除
        if (!deleteIds.isEmpty()) {
            likeMapper.batchDelete(deleteIds); // 批量删除
            log.info("批量删除点赞记录 {} 条", deleteIds.size());
        }
    }


    private void saveNewLikes(Long contentId, Set<String> userIdsToAdd, String contentType) {
        List<Like> newLikes = userIdsToAdd.stream()
                .map(userId -> {
                    userId = userId.replace("\"", "").trim();
                    Like newLike = new Like();
                    newLike.setContentId(contentId);
                    newLike.setContentType(contentType);
                    newLike.setUserId(Long.parseLong(userId));
                    newLike.setCreateTime(LocalDateTime.now());
                    return newLike;
                }).collect(Collectors.toList());

//        for (String userIdStr : userIds) {
//            // 去除多余的引号或空格，确保合法
//            userIdStr = userIdStr.replace("\"", "").trim();
//
//            try {
//                Long userId = Long.parseLong(userIdStr);
//
//                // 判断该用户是否已经点赞
//                if (!likedUserIds.contains(userId)) {
//                    // 如果用户未点赞，则创建新的点赞记录
//                    Like newLike = new Like();
//                    newLike.setContentId(contentId);
//                    newLike.setContentType(contentType);
//                    newLike.setUserId(userId);
//                    newLike.setCreateTime(LocalDateTime.now());
//                    newLikes.add(newLike); // 添加到批量插入列表
//                }
//            } catch (NumberFormatException e) {
//                // 捕获异常，忽略非法数据
//                log.info("无效的用户: {}", userIdStr);
//            }
//        }

        // 批量插入新的点赞记录
        if (!newLikes.isEmpty()) {
            likeMapper.batchInsertLikes(newLikes);
        }
    }
}
